package com.hmall.order.interceptor;

import com.hmall.order.holder.UserIdHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Author: ahcfl
 * @Date: 2021年07月31日 0:26
 * @Description:
 */
public class AuthorizationInter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String userId = request.getHeader("authorization");
        System.out.println("orderService ===== > userId = " + userId);
        System.out.println("orderService ===== > request = " + request);

        if(userId == null){
            response.setStatus(401);
            response.getWriter().print("权限不足...");
            return false;
        }

        UserIdHolder.saveUserId(Long.parseLong(userId));
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放资源
        // UserIdHolder.removeUserId();
    }
}
